package com.ruoyi.ams.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.ams.service.AmsReusingService;
import com.ruoyi.asms.service.IAsmsAssetFullInfoService;
import com.ruoyi.ams.domain.AmsAssetMaintenanceRecord;
import com.ruoyi.ams.service.IAmsAssetMaintenanceRecordService;
import com.ruoyi.ams.service.IAmsAssetTypeService;
import com.ruoyi.ams.service.IAmsOwnAddressService;
import com.ruoyi.common.core.domain.AsmsAssetFullInfo;
import com.ruoyi.common.core.domain.KeyValueVo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.system.controller.SysDeptController;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 维保信息登记Controller
 *
 * @author yfkj
 * @date 2022-05-16
 */
@RestController
@RequestMapping("/ams/maintenanceRecord")
public class AmsAssetMaintenanceRecordController extends BaseController
{
    @Autowired
    private IAmsAssetMaintenanceRecordService amsAssetMaintenanceRecordService;
    @Autowired
    private IAmsAssetTypeService amsAssetTypeService;
//    @Autowired
//    private IAsmsAssetFullInfoService assetFullInfoService;
    @Autowired
    private IAsmsAssetFullInfoService assetFullInfoService;
    @Autowired
    private IAmsOwnAddressService amsOwnAddressService;
    @Autowired
    private AmsReusingService amsReusingService;
//    @Autowired
//    private RemoteUserService remoteUserService;
//    @Autowired
//    private RemoteDeptService remoteDeptService;
    @Autowired
    private SysUserController userController;
    @Autowired
    private SysDeptController deptController;

    /**
     * 查询维保信息登记列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:list")
    @ApiOperation(value = "获取维保信息登记列表")
    @GetMapping("/getAmsAssetMaintenanceRecordList")
    public TableDataInfo getAmsAssetMaintenanceRecordList(@RequestParam(value = "status", required = false) String status,
                                                          @RequestParam(value = "code", required = false) String code)
    {
        QueryWrapper<AmsAssetMaintenanceRecord> wrapper = new QueryWrapper<>();
        if (status != null) {
            wrapper.eq(AmsAssetMaintenanceRecord.STATUS, status);
        }
        if (code != null) {
            AsmsAssetFullInfo assetFullInfo = assetFullInfoService
                    .getOne(new QueryWrapper<AsmsAssetFullInfo>()
                            .eq(AsmsAssetFullInfo.ASSET_CODE, code)
                            .or().eq(AsmsAssetFullInfo.SN, code), false);
            if (assetFullInfo != null) {
                wrapper.eq(AmsAssetMaintenanceRecord.ASSET_ID, assetFullInfo.getAssetId());
            }
        }
        wrapper.orderByDesc(AmsAssetMaintenanceRecord.MAINTENANCE_RECORD_ID);
        startPage();
        List<AmsAssetMaintenanceRecord> list = amsAssetMaintenanceRecordService.list(wrapper);

        CompletableFuture<R<Map<Long, SysUser>>> future1 = CompletableFuture.supplyAsync(() ->
                userController.getAllUsers());

        CompletableFuture<List<AsmsAssetFullInfo>> future4 = CompletableFuture.supplyAsync(() ->
                assetFullInfoService.list(new QueryWrapper<AsmsAssetFullInfo>()
                        .select(AsmsAssetFullInfo.ASSET_ID, AsmsAssetFullInfo.ASSET_CODE, AsmsAssetFullInfo.ASSET_TYPE_NAME)));

        HashMap<Long, AsmsAssetFullInfo> assetInfoMap = new HashMap<>();
        R<Map<Long, SysUser>> allUsers = new R<>();
        List<AsmsAssetFullInfo> fullInfos = new ArrayList<>();

        try {
            allUsers = future1.get();
            if (allUsers.getCode() == R.FAIL) {
                return amsReusingService.resovleError();
            }
            fullInfos = future4.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        for (AsmsAssetFullInfo fullInfo : fullInfos) {
            assetInfoMap.put(fullInfo.getAssetId(), fullInfo);
        }

        Map<Long, SysUser> userMap = allUsers.getData();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");

        for (AmsAssetMaintenanceRecord record : list) {
            if (record.getAssetId() != null) {

                AsmsAssetFullInfo assetFullInfo = assetInfoMap.get(record.getAssetId());
                if (assetFullInfo != null) {
                    record.setAssetCode(assetFullInfo.getAssetCode());
                    record.setAssetName(assetFullInfo.getAssetTypeName());
                }

            }
            if (record.getChangeTime() != null) {
                record.setChangeTimeStr(fmt.format(new Date(record.getChangeTime())));
            }
            if (record.getChangeUserId() != null) {
                SysUser sysUser = userMap.get(record.getChangeUserId());
                if (sysUser != null) {
                    record.setChangeUserName(sysUser.getNickName());
                }
            }
            if (record.getExpireTime() != null) {
                record.setExpireTimeStr(fmt.format(new Date(record.getExpireTime())));
            }
        }
        return getDataTable(list, 10);
    }


    /**
     * 获取维保信息登记详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:query")
    @ApiOperation(value = "获取维保信息登记详情")
    @GetMapping(value = "/getAmsAssetMaintenanceRecordById")
    public AjaxResult getAmsAssetMaintenanceRecordById(@RequestParam("maintenanceRecordId") Long maintenanceRecordId)
    {
        return AjaxResult.success(amsAssetMaintenanceRecordService
                .getOne(new QueryWrapper<AmsAssetMaintenanceRecord>()
                        .eq(AmsAssetMaintenanceRecord.MAINTENANCE_RECORD_ID, maintenanceRecordId)));
    }

    /**
     * 新增维保信息登记
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:add")
    @Log(title = "维保信息登记", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增维保信息登记")
    @PostMapping(value = "/addAmsAssetMaintenanceRecord")
    public AjaxResult addAmsAssetMaintenanceRecord(@RequestBody AmsAssetMaintenanceRecord amsAssetMaintenanceRecord)
    {
        if (amsAssetMaintenanceRecord.getAssetIds().length == 0) {
            return AjaxResult.error("请至少选择一个资产");
        }
        List<AmsAssetMaintenanceRecord> maintenanceRecords = new ArrayList<>();
        for (Long assetId : amsAssetMaintenanceRecord.getAssetIds()) {
            AmsAssetMaintenanceRecord maintenanceRecord = new AmsAssetMaintenanceRecord();
            BeanUtils.copyProperties(amsAssetMaintenanceRecord, maintenanceRecord);
            maintenanceRecord.setSn(amsReusingService.createSn());
            maintenanceRecord.setAssetId(assetId);
            maintenanceRecords.add(maintenanceRecord);
        }
        amsAssetMaintenanceRecordService.saveBatch(maintenanceRecords);
        return AjaxResult.success();
    }

    /**
     * 修改维保信息登记
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:edit")
    @Log(title = "维保信息登记", businessType = BusinessType.UPDATE)
    //@ApiOperation(value = "修改维保信息登记")
    @PostMapping(value = "/editAmsAssetMaintenanceRecord")
    public AjaxResult editAmsAssetMaintenanceRecord(@RequestBody AmsAssetMaintenanceRecord amsAssetMaintenanceRecord)
    {
        if (amsAssetMaintenanceRecord.getAssetIds().length == 0) {
            return AjaxResult.error("请至少选择一个资产");
        }
        List<AmsAssetMaintenanceRecord> maintenanceRecords = new ArrayList<>();
        for (Long assetId : amsAssetMaintenanceRecord.getAssetIds()) {
            AmsAssetMaintenanceRecord maintenanceRecord = new AmsAssetMaintenanceRecord();
            BeanUtils.copyProperties(amsAssetMaintenanceRecord, maintenanceRecord);
            maintenanceRecord.setAssetId(assetId);
            maintenanceRecords.add(maintenanceRecord);
        }
        amsAssetMaintenanceRecordService.updateBatchById(maintenanceRecords);
        return AjaxResult.success();
    }

    /**
     * 删除维保信息登记
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:remove")
    @Log(title = "维保信息登记", businessType = BusinessType.DELETE)
	@GetMapping("/removeAmsAssetMaintenanceRecords")
    public AjaxResult removeAmsAssetMaintenanceRecords(@RequestParam Long[] maintenanceRecordIds)
    {
        return toAjax(amsAssetMaintenanceRecordService.deleteAmsAssetMaintenanceRecordByMaintenanceRecordIds(maintenanceRecordIds));
    }
    @GetMapping("/getAmsAssetMaintenanceRecordNamesForSelect")
    //@ApiOperation(value = "获取维保信息登记名称列表用于下拉搜索")
    public AjaxResult getAmsAssetMaintenanceRecordNamesForSelect()
    {
        List<AmsAssetMaintenanceRecord> list = amsAssetMaintenanceRecordService.list();//自行加条件
        List<KeyValueVo> resultList = new ArrayList<>();
        for (AmsAssetMaintenanceRecord amsAssetMaintenanceRecord: list ) {
            KeyValueVo vo = new KeyValueVo();
            //vo.setKey(it.getId());
            //vo.setValue(it.getName());
            resultList.add(vo);
        }
        return AjaxResult.success(resultList);
    }
    /**
     * 导出维保信息登记列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:export")
    @Log(title = "维保信息登记", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAmsAssetMaintenanceRecord")
    public String exportAmsAssetMaintenanceRecord(HttpServletResponse response, AmsAssetMaintenanceRecord amsAssetMaintenanceRecord) throws IOException
    {
        List<AmsAssetMaintenanceRecord> list = amsAssetMaintenanceRecordService.selectAmsAssetMaintenanceRecordList(amsAssetMaintenanceRecord);
        ExcelUtil<AmsAssetMaintenanceRecord> util = new ExcelUtil<AmsAssetMaintenanceRecord>(AmsAssetMaintenanceRecord.class);
        util.exportExcel(response, list, "维保信息登记数据");
        return "";
    }

}
